import { Body, Controller, Del, Get, Inject, Post, Put, Query, UseGuard } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { getUserListDTO, loginDTO, registerUserDTO, updateDTO, updateUserDTO, UserDTO } from '../dto/user';
import { UserService } from '../service/user.service';
import { UserEntity } from '../entity/user.entity';
import { AuthGuard } from '../guard/auth.guard';
import { Role } from '../decorator/role.decorator';
import { IdDTO } from '../dto/images';


@Controller('user')
export class UserController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  //注册 普通用户
  @Post('/register')
  async registerUser(@Body() data: registerUserDTO) {
    const user = { ...data, status: 1 } as UserEntity;
    return this.userService.addUser(user);
  }

  //管理员 添加 用户
  @UseGuard(AuthGuard)
  @Role(['root'])
  @Post('/addUser')
  async addUser(@Body() data: UserDTO) {
    return this.userService.addUser(data as UserEntity);
  }

  //登录
  @Post('/login')
  async login(@Body() data: loginDTO) {
    return this.userService.login(data.email, data.password);
  }


  //根据token 更新个人信息
  @Put('/updateMy')
  async updateMy(@Body() data: updateDTO) {
    return this.userService.updateUser({
      ...data,
      id: this.ctx.user.id,
    });
  }

  // 管理员修改用户信息
  @UseGuard(AuthGuard)
  @Role(['root'])
  @Post('/updateUser')
  async updateUser(@Body() data: updateUserDTO) {
    return this.userService.updateUser(data as UserEntity);
  }

  //根据token 获取用户信息
  @Get('/info')
  async getInfo() {
    const data = await this.userService.getUserList({
      skip: 0,
      take: 1,
    }, { id: this.ctx.user.id });
    return data.results[0];
  }

  //获取用户列表
  @UseGuard(AuthGuard)
  @Role(['root'])
  @Get('/list')
  async getUserList(@Query() data: getUserListDTO) {
    let user = undefined;
    if (data.user) {
      user = JSON.parse(data.user);
    }
    return this.userService.getUserList(data, user);
  }

  //删除用户
  @UseGuard(AuthGuard)
  @Role(['root'])
  @Del('/del')
  async delUser(@Body() data: IdDTO) {
    if (this.ctx.user.id == data.id) {
      return { success: false, message: '删除失败,该用户已被保护' };
    }
    try {
      const { affected } = await this.userService.delete(data.id);
      return affected == 1;
    } catch (e) {
      return { success: false, message: '删除失败,未清理该用户的资源文件' };
    }
  }

}
